home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / samba.idb / usr / samba / src / source / params.c.z / params.c
Encoding:
C/C++ Source or Header  |  1998-10-28  |  19.9 KB  |  570 lines

  1. /* -------------------------------------------------------------------------- **
  2.  * Microsoft Network Services for Unix, AKA., Andrew Tridgell's SAMBA.
  3.  *
  4.  * This module Copyright (C) 1990-1998 Karl Auer
  5.  *
  6.  * Rewritten almost completely by Christopher R. Hertel
  7.  * at the University of Minnesota, September, 1997.
  8.  * This module Copyright (C) 1997-1998 by the University of Minnesota
  9.  * -------------------------------------------------------------------------- **
  10.  *
  11.  * This program is free software; you can redistribute it and/or modify
  12.  * it under the terms of the GNU General Public License as published by
  13.  * the Free Software Foundation; either version 2 of the License, or
  14.  * (at your option) any later version.
  15.  *
  16.  * This program is distributed in the hope that it will be useful,
  17.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  19.  * GNU General Public License for more details.
  20.  *
  21.  * You should have received a copy of the GNU General Public License
  22.  * along with this program; if not, write to the Free Software
  23.  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  24.  *
  25.  * -------------------------------------------------------------------------- **
  26.  *
  27.  * Module name: params
  28.  *
  29.  * -------------------------------------------------------------------------- **
  30.  *
  31.  *  This module performs lexical analysis and initial parsing of a
  32.  *  Windows-like parameter file.  It recognizes and handles four token
  33.  *  types:  section-name, parameter-name, parameter-value, and
  34.  *  end-of-file.  Comments and line continuation are handled
  35.  *  internally.
  36.  *
  37.  *  The entry point to the module is function pm_process().  This
  38.  *  function opens the source file, calls the Parse() function to parse
  39.  *  the input, and then closes the file when either the EOF is reached
  40.  *  or a fatal error is encountered.
  41.  *
  42.  *  A sample parameter file might look like this:
  43.  *
  44.  *  [section one]
  45.  *  parameter one = value string
  46.  *  parameter two = another value
  47.  *  [section two]
  48.  *  new parameter = some value or t'other
  49.  *
  50.  *  The parameter file is divided into sections by section headers:
  51.  *  section names enclosed in square brackets (eg. [section one]).
  52.  *  Each section contains parameter lines, each of which consist of a
  53.  *  parameter name and value delimited by an equal sign.  Roughly, the
  54.  *  syntax is:
  55.  *
  56.  *    <file>            :==  { <section> } EOF
  57.  *
  58.  *    <section>         :==  <section header> { <parameter line> }
  59.  *
  60.  *    <section header>  :==  '[' NAME ']'
  61.  *
  62.  *    <parameter line>  :==  NAME '=' VALUE '\n'
  63.  *
  64.  *  Blank lines and comment lines are ignored.  Comment lines are lines
  65.  *  beginning with either a semicolon (';') or a pound sign ('#').
  66.  *
  67.  *  All whitespace in section names and parameter names is compressed
  68.  *  to single spaces.  Leading and trailing whitespace is stipped from
  69.  *  both names and values.
  70.  *
  71.  *  Only the first equals sign in a parameter line is significant.
  72.  *  Parameter values may contain equals signs, square brackets and
  73.  *  semicolons.  Internal whitespace is retained in parameter values,
  74.  *  with the exception of the '\r' character, which is stripped for
  75.  *  historic reasons.  Parameter names may not start with a left square
  76.  *  bracket, an equal sign, a pound sign, or a semicolon, because these
  77.  *  are used to identify other tokens.
  78.  *
  79.  * -------------------------------------------------------------------------- **
  80.  */
  81.  
  82. #include "includes.h"
  83.  
  84. /* -------------------------------------------------------------------------- **
  85.  * Constants...
  86.  */
  87.  
  88. #define BUFR_INC 1024
  89.  
  90.  
  91. /* -------------------------------------------------------------------------- **
  92.  * Variables...
  93.  *
  94.  *  DEBUGLEVEL  - The ubiquitous DEBUGLEVEL.  This determines which DEBUG()
  95.  *                messages will be produced.
  96.  *  bufr        - pointer to a global buffer.  This is probably a kludge,
  97.  *                but it was the nicest kludge I could think of (for now).
  98.  *  bSize       - The size of the global buffer <bufr>.
  99.  */
  100.  
  101. extern int DEBUGLEVEL;
  102.  
  103. static char *bufr  = NULL;
  104. static int   bSize = 0;
  105.  
  106. /* -------------------------------------------------------------------------- **
  107.  * Functions...
  108.  */
  109.  
  110. static int EatWhitespace( FILE *InFile )
  111.   /* ------------------------------------------------------------------------ **
  112.    * Scan past whitespace (see ctype(3C)) and return the first non-whitespace
  113.    * character, or newline, or EOF.
  114.    *
  115.    *  Input:  InFile  - Input source.
  116.    *
  117.    *  Output: The next non-whitespace character in the input stream.
  118.    *
  119.    *  Notes:  Because the config files use a line-oriented grammar, we
  120.    *          explicitly exclude the newline character from the list of
  121.    *          whitespace characters.
  122.    *        - Note that both EOF (-1) and the nul character ('\0') are
  123.    *          considered end-of-file markers.
  124.    *
  125.    * ------------------------------------------------------------------------ **
  126.    */
  127.   {
  128.   int c;
  129.  
  130.   for( c = getc( InFile ); isspace( c ) && ('\n' != c); c = getc( InFile ) )
  131.     ;
  132.   return( c );
  133.   } /* EatWhitespace */
  134.  
  135. static int EatComment( FILE *InFile )
  136.   /* ------------------------------------------------------------------------ **
  137.    * Scan to the end of a comment.
  138.    *
  139.    *  Input:  InFile  - Input source.
  140.    *
  141.    *  Output: The character that marks the end of the comment.  Normally,
  142.    *          this will be a newline, but it *might* be an EOF.
  143.    *
  144.    *  Notes:  Because the config files use a line-oriented grammar, we
  145.    *          explicitly exclude the newline character from the list of
  146.    *          whitespace characters.
  147.    *        - Note that both EOF (-1) and the nul character ('\0') are
  148.    *          considered end-of-file markers.
  149.    *
  150.    * ------------------------------------------------------------------------ **
  151.    */
  152.   {
  153.   int c;
  154.  
  155.   for( c = getc( InFile ); ('\n'!=c) && (EOF!=c) && (c>0); c = getc( InFile ) )
  156.     ;
  157.   return( c );
  158.   } /* EatComment */
  159.  
  160. static int Continuation( char *line, int pos )
  161.   /* ------------------------------------------------------------------------ **
  162.    * Scan backards within a string to discover if the last non-whitespace
  163.    * character is a line-continuation character ('\\').
  164.    *
  165.    *  Input:  line  - A pointer to a buffer containing the string to be
  166.    *                  scanned.
  167.    *          pos   - This is taken to be the offset of the end of the
  168.    *                  string.  This position is *not* scanned.
  169.    *
  170.    *  Output: The offset of the '\\' character if it was found, or -1 to
  171.    *          indicate that it was not.
  172.    *
  173.    * ------------------------------------------------------------------------ **
  174.    */
  175.   {
  176.   pos--;
  177.   while( (pos >= 0) && isspace(line[pos]) )
  178.      pos--;
  179.  
  180.   return( ((pos >= 0) && ('\\' == line[pos])) ? pos : -1 );
  181.   } /* Continuation */
  182.  
  183.  
  184. static BOOL Section( FILE *InFile, BOOL (*sfunc)(char *) )
  185.   /* ------------------------------------------------------------------------ **
  186.    * Scan a section name, and pass the name to function sfunc().
  187.    *
  188.    *  Input:  InFile  - Input source.
  189.    *          sfunc   - Pointer to the function to be called if the section
  190.    *                    name is successfully read.
  191.    *
  192.    *  Output: True if the section name was read and True was returned from
  193.    *          <sfunc>.  False if <sfunc> failed or if a lexical error was
  194.    *          encountered.
  195.    *
  196.    * ------------------------------------------------------------------------ **
  197.    */
  198.   {
  199.   int   c;
  200.   int   i;
  201.   int   end;
  202.   char *func  = "params.c:Section() -";
  203.  
  204.   i = 0;      /* <i> is the offset of the next free byte in bufr[] and  */
  205.   end = 0;    /* <end> is the current "end of string" offset.  In most  */
  206.               /* cases these will be the same, but if the last          */
  207.               /* character written to bufr[] is a space, then <end>     */
  208.               /* will be one less than <i>.                             */
  209.  
  210.   c = EatWhitespace( InFile );    /* We've already got the '['.  Scan */
  211.                                   /* past initial white space.        */
  212.  
  213.   while( (EOF != c) && (c > 0) )
  214.     {
  215.  
  216.     /* Check that the buffer is big enough for the next character. */
  217.     if( i > (bSize - 2) )
  218.       {
  219.       bSize += BUFR_INC;
  220.       bufr   = Realloc( bufr, bSize );
  221.       if( NULL == bufr )
  222.         {
  223.         DEBUG(0, ("%s Memory re-allocation failure.", func) );
  224.         return( False );
  225.         }
  226.       }
  227.  
  228.     /* Handle a single character. */
  229.     switch( c )
  230.       {
  231.       case ']':                       /* Found the closing bracket.         */
  232.         bufr[end] = '\0';
  233.         if( 0 == end )                  /* Don't allow an empty name.       */
  234.           {
  235.           DEBUG(0, ("%s Empty section name in configuration file.\n", func ));
  236.           return( False );
  237.           }
  238.         if( !sfunc( bufr ) )            /* Got a valid name.  Deal with it. */
  239.           return( False );
  240.         (void)EatComment( InFile );     /* Finish off the line.             */
  241.         return( True );
  242.  
  243.       case '\n':                      /* Got newline before closing ']'.    */
  244.         i = Continuation( bufr, i );    /* Check for line continuation.     */
  245.         if( i < 0 )
  246.           {
  247.           bufr[end] = '\0';
  248.           DEBUG(0, ("%s Badly formed line in configuration file: %s\n",
  249.                    func, bufr ));
  250.           return( False );
  251.           }
  252.         end = ( (i > 0) && (' ' == bufr[i - 1]) ) ? (i - 1) : (i);
  253.         c = getc( InFile );             /* Continue with next line.         */
  254.         break;
  255.  
  256.       default:                        /* All else are a valid name chars.   */
  257.         if( isspace( c ) )              /* One space per whitespace region. */
  258.           {
  259.           bufr[end] = ' ';
  260.           i = end + 1;
  261.           c = EatWhitespace( InFile );
  262.           }
  263.         else                            /* All others copy verbatim.        */
  264.           {
  265.           bufr[i++] = c;
  266.           end = i;
  267.           c = getc( InFile );
  268.           }
  269.       }
  270.     }
  271.  
  272.   /* We arrive here if we've met the EOF before the closing bracket. */
  273.   DEBUG(0, ("%s Unexpected EOF in the configuration file: %s\n", func, bufr ));
  274.   return( False );
  275.   } /* Section */
  276.  
  277. static BOOL Parameter( FILE *InFile, BOOL (*pfunc)(char *, char *), int c )
  278.   /* ------------------------------------------------------------------------ **
  279.    * Scan a parameter name and value, and pass these two fields to pfunc().
  280.    *
  281.    *  Input:  InFile  - The input source.
  282.    *          pfunc   - A pointer to the function that will be called to
  283.    *                    process the parameter, once it has been scanned.
  284.    *          c       - The first character of the parameter name, which
  285.    *                    would have been read by Parse().  Unlike a comment
  286.    *                    line or a section header, there is no lead-in
  287.    *                    character that can be discarded.
  288.    *
  289.    *  Output: True if the parameter name and value were scanned and processed
  290.    *          successfully, else False.
  291.    *
  292.    *  Notes:  This function is in two parts.  The first loop scans the
  293.    *          parameter name.  Internal whitespace is compressed, and an
  294.    *          equal sign (=) terminates the token.  Leading and trailing
  295.    *          whitespace is discarded.  The second loop scans the parameter
  296.    *          value.  When both have been successfully identified, they are
  297.    *          passed to pfunc() for processing.
  298.    *
  299.    * ------------------------------------------------------------------------ **
  300.    */
  301.   {
  302.   int   i       = 0;    /* Position within bufr. */
  303.   int   end     = 0;    /* bufr[end] is current end-of-string. */
  304.   int   vstart  = 0;    /* Starting position of the parameter value. */
  305.   char *func    = "params.c:Parameter() -";
  306.  
  307.   /* Read the parameter name. */
  308.   while( 0 == vstart )  /* Loop until we've found the start of the value. */
  309.     {
  310.  
  311.     if( i > (bSize - 2) )       /* Ensure there's space for next char.    */
  312.       {
  313.       bSize += BUFR_INC;
  314.       bufr   = Realloc( bufr, bSize );
  315.       if( NULL == bufr )
  316.         {
  317.         DEBUG(0, ("%s Memory re-allocation failure.", func) );
  318.         return( False );
  319.         }
  320.       }
  321.  
  322.     switch( c )
  323.       {
  324.       case '=':                 /* Equal sign marks end of param name. */
  325.         if( 0 == end )              /* Don't allow an empty name.      */
  326.           {
  327.           DEBUG(0, ("%s Invalid parameter name in config. file.\n", func ));
  328.           return( False );
  329.           }
  330.         bufr[end++] = '\0';         /* Mark end of string & advance.   */
  331.         i       = end;              /* New string starts here.         */
  332.         vstart  = end;              /* New string is parameter value.  */
  333.         bufr[i] = '\0';             /* New string is nul, for now.     */
  334.         break;
  335.  
  336.       case '\n':                /* Find continuation char, else error. */
  337.         i = Continuation( bufr, i );
  338.         if( i < 0 )
  339.           {
  340.           bufr[end] = '\0';
  341.           DEBUG(1,("%s Ignoring badly formed line in configuration file: %s\n",
  342.                    func, bufr ));
  343.           return( True );
  344.           }
  345.         end = ( (i > 0) && (' ' == bufr[i - 1]) ) ? (i - 1) : (i);
  346.         c = getc( InFile );       /* Read past eoln.                   */
  347.         break;
  348.  
  349.       case '\0':                /* Shouldn't have EOF within param name. */
  350.       case EOF:
  351.         bufr[i] = '\0';
  352.         DEBUG(1,("%s Unexpected end-of-file at: %s\n", func, bufr ));
  353.         return( True );
  354.  
  355.       default:
  356.         if( isspace( c ) )     /* One ' ' per whitespace region.       */
  357.           {
  358.           bufr[end] = ' ';
  359.           i = end + 1;
  360.           c = EatWhitespace( InFile );
  361.           }
  362.         else                   /* All others verbatim.                 */
  363.           {
  364.           bufr[i++] = c;
  365.           end = i;
  366.           c = getc( InFile );
  367.           }
  368.       }
  369.     }
  370.  
  371.   /* Now parse the value. */
  372.   c = EatWhitespace( InFile );  /* Again, trim leading whitespace. */
  373.   while( (EOF !=c) && (c > 0) )
  374.     {
  375.  
  376.     if( i > (bSize - 2) )       /* Make sure there's enough room. */
  377.       {
  378.       bSize += BUFR_INC;
  379.       bufr   = Realloc( bufr, bSize );
  380.       if( NULL == bufr )
  381.         {
  382.         DEBUG(0, ("%s Memory re-allocation failure.", func) );
  383.         return( False );
  384.         }
  385.       }
  386.  
  387.     switch( c )
  388.       {
  389.       case '\r':              /* Explicitly remove '\r' because the older */
  390.         c = getc( InFile );   /* version called fgets_slash() which also  */
  391.         break;                /* removes them.                            */
  392.  
  393.       case '\n':              /* Marks end of value unless there's a '\'. */
  394.         i = Continuation( bufr, i );
  395.         if( i < 0 )
  396.           c = 0;
  397.         else
  398.           {
  399.           for( end = i; (end >= 0) && isspace(bufr[end]); end-- )
  400.             ;
  401.           c = getc( InFile );
  402.           }
  403.         break;
  404.  
  405.       default:               /* All others verbatim.  Note that spaces do */
  406.         bufr[i++] = c;       /* not advance <end>.  This allows trimming  */
  407.         if( !isspace( c ) )  /* of whitespace at the end of the line.     */
  408.           end = i;
  409.         c = getc( InFile );
  410.         break;
  411.       }
  412.     }
  413.   bufr[end] = '\0';          /* End of value. */
  414.  
  415.   return( pfunc( bufr, &bufr[vstart] ) );   /* Pass name & value to pfunc().  */
  416.   } /* Parameter */
  417.  
  418. static BOOL Parse( FILE *InFile,
  419.                    BOOL (*sfunc)(char *),
  420.                    BOOL (*pfunc)(char *, char *) )
  421.   /* ------------------------------------------------------------------------ **
  422.    * Scan & parse the input.
  423.    *
  424.    *  Input:  InFile  - Input source.
  425.    *          sfunc   - Function to be called when a section name is scanned.
  426.    *                    See Section().
  427.    *          pfunc   - Function to be called when a parameter is scanned.
  428.    *                    See Parameter().
  429.    *
  430.    *  Output: True if the file was successfully scanned, else False.
  431.    *
  432.    *  Notes:  The input can be viewed in terms of 'lines'.  There are four
  433.    *          types of lines:
  434.    *            Blank      - May contain whitespace, otherwise empty.
  435.    *            Comment    - First non-whitespace character is a ';' or '#'.
  436.    *                         The remainder of the line is ignored.
  437.    *            Section    - First non-whitespace character is a '['.
  438.    *            Parameter  - The default case.
  439.    * 
  440.    * ------------------------------------------------------------------------ **
  441.    */
  442.   {
  443.   int    c;
  444.  
  445.   c = EatWhitespace( InFile );
  446.   while( (EOF != c) && (c > 0) )
  447.     {
  448.     switch( c )
  449.       {
  450.       case '\n':                        /* Blank line. */
  451.         c = EatWhitespace( InFile );
  452.         break;
  453.  
  454.       case ';':                         /* Comment line. */
  455.       case '#':
  456.         c = EatComment( InFile );
  457.         break;
  458.  
  459.       case '[':                         /* Section Header. */
  460.         if( !Section( InFile, sfunc ) )
  461.           return( False );
  462.         c = EatWhitespace( InFile );
  463.         break;
  464.  
  465.       case '\\':                        /* Bogus backslash. */
  466.         c = EatWhitespace( InFile );
  467.         break;
  468.  
  469.       default:                          /* Parameter line. */
  470.         if( !Parameter( InFile, pfunc, c ) )
  471.           return( False );
  472.         c = EatWhitespace( InFile );
  473.         break;
  474.       }
  475.     }
  476.   return( True );
  477.   } /* Parse */
  478.  
  479. static FILE *OpenConfFile( char *FileName )
  480.   /* ------------------------------------------------------------------------ **
  481.    * Open a configuration file.
  482.    *
  483.    *  Input:  FileName  - The pathname of the config file to be opened.
  484.    *
  485.    *  Output: A pointer of type (FILE *) to the opened file, or NULL if the
  486.    *          file could not be opened.
  487.    *
  488.    * ------------------------------------------------------------------------ **
  489.    */
  490.   {
  491.   FILE *OpenedFile;
  492.   char *func = "params.c:OpenConfFile() -";
  493.  
  494.   if( NULL == FileName || 0 == *FileName )
  495.     {
  496.     DEBUG( 0, ("%s No configuration filename specified.\n", func) );
  497.     return( NULL );
  498.     }
  499.  
  500.   OpenedFile = fopen( FileName, "r" );
  501.   if( NULL == OpenedFile )
  502.     {
  503.     DEBUG( 0,
  504.       ("%s Unable to open configuration file \"%s\":\n\t%s\n",
  505.       func, FileName, strerror(errno)) );
  506.     }
  507.  
  508.   return( OpenedFile );
  509.   } /* OpenConfFile */
  510.  
  511. BOOL pm_process( char *FileName,
  512.                  BOOL (*sfunc)(char *),
  513.                  BOOL (*pfunc)(char *, char *) )
  514.   /* ------------------------------------------------------------------------ **
  515.    * Process the named parameter file.
  516.    *
  517.    *  Input:  FileName  - The pathname of the parameter file to be opened.
  518.    *          sfunc     - A pointer to a function that will be called when
  519.    *                      a section name is discovered.
  520.    *          pfunc     - A pointer to a function that will be called when
  521.    *                      a parameter name and value are discovered.
  522.    *
  523.    *  Output: TRUE if the file was successfully parsed, else FALSE.
  524.    *
  525.    * ------------------------------------------------------------------------ **
  526.    */
  527.   {
  528.   int   result;
  529.   FILE *InFile;
  530.   char *func = "params.c:pm_process() -";
  531.  
  532.   InFile = OpenConfFile( FileName );          /* Open the config file. */
  533.   if( NULL == InFile )
  534.     return( False );
  535.  
  536.   DEBUG( 3, ("%s Processing configuration file \"%s\"\n", func, FileName) );
  537.  
  538.   if( NULL != bufr )                          /* If we already have a buffer */
  539.     result = Parse( InFile, sfunc, pfunc );   /* (recursive call), then just */
  540.                                               /* use it.                     */
  541.  
  542.   else                                        /* If we don't have a buffer   */
  543.     {                                         /* allocate one, then parse,   */
  544.     bSize = BUFR_INC;                         /* then free.                  */
  545.     bufr = (char *)malloc( bSize );
  546.     if( NULL == bufr )
  547.       {
  548.       DEBUG(0,("%s memory allocation failure.\n", func));
  549.       fclose(InFile);
  550.       return( False );
  551.       }
  552.     result = Parse( InFile, sfunc, pfunc );
  553.     free( bufr );
  554.     bufr  = NULL;
  555.     bSize = 0;
  556.     }
  557.  
  558.   fclose(InFile);
  559.  
  560.   if( !result )                               /* Generic failure. */
  561.     {
  562.     DEBUG(0,("%s Failed.  Error returned from params.c:parse().\n", func));
  563.     return( False );
  564.     }
  565.  
  566.   return( True );                             /* Generic success. */
  567.   } /* pm_process */
  568.  
  569. /* -------------------------------------------------------------------------- */
  570.